#!/usr/bin/env ruby

#Add several methods to the File class
require 'ftools'

def debug(msg)
  if (DEBUG)
    puts "DEBUG: " + msg.to_s  
  end
  
end

#
# Directory handler, check given folder and insert images into DB
#
class DirHandler

  def initialize()
    @directory = ""
    @image_files = nil
    @dbh = DatabaseHandler.new()
    @dbh.connect
  end
  attr_accessor :directory, :image_files
  attr_writer :directory, :image_files
  
  # set new directory
  # returns 1 if directory, 0 else
  def new_dir(path)
    @directory = path
    if(File::directory?(path))
      return true
    else
      return false
    end
  end
  
  # get files from path
  # @returns list of files
  def get_files
    img_files = Array.new
    
    Dir.chdir(@directory)
    
    # cycle through each image file
    Dir.foreach(@directory) do |entry|
      
      if entry.include?(".JPG")
          if (!file_already_in_DB(entry))
            img_files.push(entry)
          end
      
      elsif entry.include?(".jpg")
          if (!file_already_in_DB(entry))
            img_files.push(entry)
          end
        
      end
      
      #debug("File " + entry)
    end
    @image_files = img_files
    
    return img_files
    
  end
  
  # check if file is already ion DB
  def file_already_in_DB(filename)
    result = @dbh.query("SELECT id from image where filename = '#{filename}'")
    r = result.fetch_row
    
    if (r == nil)
      return false
    else
      return true
    end
    
  end
  
  # copy files from given directory to local image storage
  def copy_images_to_storage
    @image_files.each do |file|
      #debug("Copy from: " + @directory)
      File.copy(@directory +"\\"+ file, IMAGES_DIR)        
    end
  end  
  
end